package com.ruoyi.message.handler;


import com.ruoyi.message.service.WebSocketEndPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: Zhuhongyang
 * @description:
 * @createTime: 2023/7/17
 */
public class WebSocketHandler {

    private static final Logger log = LoggerFactory.getLogger(WebSocketHandler.class);

    private static final Map<Session, Boolean> sessionBooleanMap = new ConcurrentHashMap<>();

    /**
     * 给指定用户发送信息
     * @param session
     * @param msg
     */
    public static void sendMessage(Session session, String msg){
        if (session == null){
            return;
        }
        final RemoteEndpoint.Basic basic = session.getBasicRemote();
        if (basic == null){
            return;
        }
        try {
            synchronized (session){
                // log.info("发送的消息体内容:["+msg+"]");
                basic.sendText(msg);
            }
        } catch (IOException e) {
            log.error("sendText Exception:{}", e.getMessage());
        }
    }

    // 新的发送二进制数据的方法
    public static void sendBinary(Session session, byte[] data) {
        synchronized (session) {
            if (sessionBooleanMap.containsKey(session)) {
                return;
            }
            sessionBooleanMap.put(session, true);
        }

        try {
            ByteBuffer buffer = ByteBuffer.wrap(data);
            if (session.isOpen()) {
                synchronized (session) {
                    session.getBasicRemote().sendBinary(buffer);
                    sessionBooleanMap.remove(session);
                }
            }
        } catch (Exception e) {
            sessionBooleanMap.remove(session);
            log.error("发送二进制数据时发生错误: {}", e.getMessage());
        }
    }


    /**
     * 给所有的在线用户发送消息
     * @param message
     */
    public static void sendMessageAll(String message){
        log.info("广播：群发消息");
        WebSocketPool.sessionMap().forEach((key, session) -> sendMessage(session, message));
    }
}
